package edu.uoc.tdp.pac4.client.gestion;

import edu.uoc.tdp.pac4.EAssistencia;
import edu.uoc.tdp.pac4.beans.Matricula;
import edu.uoc.tdp.pac4.remote.GestAcademica;
import edu.uoc.tdp.pac4.util.ComboItem;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * Formulario de gestión de matrículas.
 * 
 * @author eSupport Netbeans
 */
public class PnlMatriculaGestor extends javax.swing.JDialog 
{
   private GestAcademica manager;
   private LanguageUtils language;
   private List<ComboItem> estados;
   private ArrayList<Matricula> matriculas;

   /**
    * Creates new form PnlMatriculaGestor
    */
   public PnlMatriculaGestor(java.awt.Frame parent, boolean modal, GestAcademica manager, LanguageUtils language) 
   {
      super(parent, modal);
      initComponents();
      
      setLocationRelativeTo(null);
      pnlFilter.setVisible(false);

      this.manager = manager;
      this.language = language;
      
      setLanguage();
      fillFilterPanel();
      fillForm();
   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   private void initComponents() {

      jScrollPane1 = new javax.swing.JScrollPane();
      grdTable = new javax.swing.JTable();
      jToolBar1 = new javax.swing.JToolBar();
      cmdAdd = new javax.swing.JButton();
      cmdDelete = new javax.swing.JButton();
      jSeparator1 = new javax.swing.JToolBar.Separator();
      cmdFilter = new javax.swing.JToggleButton();
      cmdClose = new javax.swing.JButton();
      pnlFilter = new javax.swing.JPanel();
      lblAlumno = new javax.swing.JLabel();
      txtName = new javax.swing.JTextField();
      lblNIF = new javax.swing.JLabel();
      txtNif = new javax.swing.JTextField();
      lblEstado = new javax.swing.JLabel();
      cboEstado = new javax.swing.JComboBox();
      cmdSetFilter = new javax.swing.JButton();
      cmdFilterClean = new javax.swing.JButton();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle("Gestión de matriculas");

      grdTable.setModel(new javax.swing.table.DefaultTableModel(
         new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
         },
         new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
         }
      ));
      jScrollPane1.setViewportView(grdTable);

      jToolBar1.setRollover(true);

      cmdAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/book--plus.png"))); // NOI18N
      cmdAdd.setText("Aceptar / Editar");
      cmdAdd.setFocusable(false);
      cmdAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
      cmdAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
      cmdAdd.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdAddActionPerformed(evt);
         }
      });
      jToolBar1.add(cmdAdd);

      cmdDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/book--minus.png"))); // NOI18N
      cmdDelete.setText("Anular");
      cmdDelete.setFocusable(false);
      cmdDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
      cmdDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
      cmdDelete.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdDeleteActionPerformed(evt);
         }
      });
      jToolBar1.add(cmdDelete);
      jToolBar1.add(jSeparator1);

      cmdFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/funnel.png"))); // NOI18N
      cmdFilter.setText("Filtrar");
      cmdFilter.setFocusable(false);
      cmdFilter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
      cmdFilter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
      cmdFilter.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdFilterActionPerformed(evt);
         }
      });
      jToolBar1.add(cmdFilter);

      cmdClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/arrow-curve-180.png"))); // NOI18N
      cmdClose.setText("Cerrar");
      cmdClose.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdCloseActionPerformed(evt);
         }
      });

      pnlFilter.setBorder(javax.swing.BorderFactory.createEtchedBorder());

      lblAlumno.setText("Alumno");

      lblNIF.setText("NIF");

      lblEstado.setText("Estado matricula");

      cmdSetFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/funnel--plus.png"))); // NOI18N
      cmdSetFilter.setText("Aplicar");
      cmdSetFilter.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdSetFilterActionPerformed(evt);
         }
      });

      cmdFilterClean.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/eraser.png"))); // NOI18N
      cmdFilterClean.setText("Limpiar");
      cmdFilterClean.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdFilterCleanActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout pnlFilterLayout = new javax.swing.GroupLayout(pnlFilter);
      pnlFilter.setLayout(pnlFilterLayout);
      pnlFilterLayout.setHorizontalGroup(
         pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(pnlFilterLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(lblAlumno)
               .addComponent(lblNIF))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(txtNif, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addGroup(pnlFilterLayout.createSequentialGroup()
                  .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGap(18, 18, 18)
                  .addComponent(lblEstado)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                  .addComponent(cboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
            .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
               .addComponent(cmdSetFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(cmdFilterClean, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
      );
      pnlFilterLayout.setVerticalGroup(
         pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlFilterLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(lblAlumno)
               .addComponent(lblEstado)
               .addComponent(cboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(cmdFilterClean))
            .addGap(6, 6, 6)
            .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(txtNif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(lblNIF)
               .addComponent(cmdSetFilter))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
               .addComponent(pnlFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE)
               .addGroup(layout.createSequentialGroup()
                  .addGap(0, 0, Short.MAX_VALUE)
                  .addComponent(cmdClose)))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(pnlFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cmdClose)
            .addContainerGap())
      );

      pack();
   }// </editor-fold>//GEN-END:initComponents

   private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAddActionPerformed

      if (grdTable.getSelectedRow() < 0)
      {
         JOptionPane.showMessageDialog(null,
                                       language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_WARN_SELECTMATRICULA),
                                       language.getProperty(EAssistencia.APP_TITLE),
                                       JOptionPane.WARNING_MESSAGE);
         return;
      }

      // Obtiene el ID del matricula a editar
      Matricula matricula = matriculas.get(grdTable.getSelectedRow());
      
      try
      {
         PnlMatricula form = new PnlMatricula(null, true, manager, language, matricula.getId(), PnlMatricula.DialogMode.AceptarMatricula);
         form.setLocationRelativeTo(null);
         form.setVisible(true);
      }
      catch (Exception ex)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty(EAssistencia.ERROR_GENERIC) + "\n" + language.getProperty(EAssistencia.ERROR_DETAILS) + ":\n\n" + ex.getMessage(), 
                                       language.getProperty(EAssistencia.APP_TITLE), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }

      fillForm();
   }//GEN-LAST:event_cmdAddActionPerformed

   private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCloseActionPerformed

      // Cierra el formulario
      this.dispose();
   }//GEN-LAST:event_cmdCloseActionPerformed

   private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDeleteActionPerformed
      
      if (grdTable.getSelectedRow() < 0)
      {
         JOptionPane.showMessageDialog(null,
                                       language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_WARN_SELECTMATRICULA),
                                       language.getProperty(EAssistencia.APP_TITLE),
                                       JOptionPane.WARNING_MESSAGE);
         return;
      }
      
      // Confirma la acción antes de efectuarla
      if (JOptionPane.showConfirmDialog(null,
                                        language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_WARN_ASKDELETE),
                                        language.getProperty(EAssistencia.APP_TITLE),
                                        JOptionPane.YES_NO_OPTION,
                                        JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)
      {
         return;
      }
      
      try 
      {
         // Obtiene el matricula seleccionado y la marca como ANULADA
         Matricula matricula = matriculas.get(grdTable.getSelectedRow());
         manager.deleteMatricula(matricula.getId());
         
         // Refresca el listado
         fillForm();
      } 
      catch (Exception ex) 
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty(EAssistencia.ERROR_GENERIC) + "\n" + language.getProperty(EAssistencia.ERROR_DETAILS) + ":\n\n" + ex.getMessage(), 
                                       language.getProperty(EAssistencia.APP_TITLE), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      
   }//GEN-LAST:event_cmdDeleteActionPerformed

   private void cmdFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFilterActionPerformed
      
      pnlFilter.setVisible(cmdFilter.isSelected());
      
      // Si se oculta el filtro, se regenera la lista completa
      if (!pnlFilter.isVisible())
      {
         fillForm();
      }
      else
      {
         fillFilterPanel();
      }
      
   }//GEN-LAST:event_cmdFilterActionPerformed

   private void cmdSetFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSetFilterActionPerformed
      
      int estado;
      
      if (cboEstado.getSelectedIndex() >= 0)
      {
         estado = estados.get(cboEstado.getSelectedIndex()).getId();
      }
      else
      {
         estado = -1;
      }
      
      fillForm(txtName.getText(), txtNif.getText(), estado);
      
   }//GEN-LAST:event_cmdSetFilterActionPerformed

   private void cmdFilterCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFilterCleanActionPerformed
      
      fillFilterPanel();
      
   }//GEN-LAST:event_cmdFilterCleanActionPerformed

   private void setLanguage()
   {
      this.setTitle(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_TITLE));
      cmdAdd.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ACEPTAR));
      cmdDelete.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_CANCELAR));
      cmdFilter.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_FILTER));
      lblAlumno.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ALUMNO));
      lblNIF.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_NIF));
      lblEstado.setText(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ESTADO));
      cmdFilterClean.setText(language.getProperty(EAssistencia.FORM_COMMON_CLEAN));
      cmdSetFilter.setText(language.getProperty(EAssistencia.FORM_COMMON_APPLY));
      cmdClose.setText(language.getProperty(EAssistencia.FORM_COMMON_CLOSE));
   }
   
   /**
    * Rellena los controles del panel de filtrado.
    */
   private void fillFilterPanel()
   {
      // Rellena el combo de filtros
      estados = new ArrayList<ComboItem>();
      estados.add(new ComboItem(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ESTADO_NOFILTER), -1));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_PENDIENTE, language), Matricula.MATRICULA_ESTADO_PENDIENTE));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_ACEPTADA, language), Matricula.MATRICULA_ESTADO_ACEPTADA));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_ANULADA, language), Matricula.MATRICULA_ESTADO_ANULADA));
      cboEstado.removeAll();
      cboEstado.setModel(new DefaultComboBoxModel(estados.toArray()));
      
      txtName.setText("");
      txtNif.setText("");
   }
   
   /**
    * Genera el listado.
    */
   private void fillForm()
   {
      fillForm("", "", -1);
   }
   
   /**
    * Genera el listado.
    */
   private void fillForm(String name, String nif, int estado)
   {
      SimpleDateFormat sdf = new SimpleDateFormat(language.getProperty(EAssistencia.FORMAT_SHORTDATE));
      DecimalFormat df = new DecimalFormat(language.getProperty(EAssistencia.FORMAT_NUMERIC_ID));
      
      // Rellena la tabla
      ArrayList<String> header = new ArrayList<String>();   // cabecera
      header.add("ID");
      header.add(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_NIF));
      header.add(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ALUMNO));
      header.add(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_CURSO));
      header.add(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_GRUPO));
      header.add(language.getProperty(EAssistencia.FORM_PNLMATRICULAGESTOR_ESTADO));
      
      String[][] gridData;
      ArrayList<String> row;

      try 
      {
         matriculas = manager.getMatriculas(name, nif, estado);
         gridData = new String[matriculas.size()][8];
         int i = 0;
         for (Matricula matricula : matriculas)
         {
            gridData[i][0] = df.format(matricula.getId());
            gridData[i][1] = matricula.getUsuarioNif();
            gridData[i][2] = matricula.getUsuarioNombre();
            gridData[i][3] = matricula.getCursoNombre();
            gridData[i][4] = matricula.getGrupoNombre();
            gridData[i][5] = Matricula.getStatusName(matricula.getEstado(), language);
            i++;
         }
         
         // Evita que las celdas se puedan editar
         grdTable.setModel(new DefaultTableModel(gridData, header.toArray()) { 
            @Override public boolean isCellEditable(int row, int column)
            { 
               return false; 
            } 
         });
         // grdTable.setModel(new DefaultTableModel(gridData, header.toArray()));
      } 
      catch (Exception ex) 
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty(EAssistencia.ERROR_GENERIC) + "\n" + language.getProperty(EAssistencia.ERROR_DETAILS) + ":\n\n" + ex.getMessage(), 
                                       language.getProperty(EAssistencia.APP_TITLE), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
   }

   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JComboBox cboEstado;
   private javax.swing.JButton cmdAdd;
   private javax.swing.JButton cmdClose;
   private javax.swing.JButton cmdDelete;
   private javax.swing.JToggleButton cmdFilter;
   private javax.swing.JButton cmdFilterClean;
   private javax.swing.JButton cmdSetFilter;
   private javax.swing.JTable grdTable;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JToolBar.Separator jSeparator1;
   private javax.swing.JToolBar jToolBar1;
   private javax.swing.JLabel lblAlumno;
   private javax.swing.JLabel lblEstado;
   private javax.swing.JLabel lblNIF;
   private javax.swing.JPanel pnlFilter;
   private javax.swing.JTextField txtName;
   private javax.swing.JTextField txtNif;
   // End of variables declaration//GEN-END:variables
}
